import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import qs from 'qs'
import { getToken, clearLogin, setToken } from "@/utils/myAuth"
import router from '@/router/index'

const settingFile = require('@/settings.js') //在settings.js配置了统一的路径代码,在这这个地方引入
    // 什么是跨域?
    // 出于浏览器的同源安全策略,只要存在协议,域名,端口任意一个不同的ajax请求,都是跨域请求.
    // 如何解决跨域?
    // 1. 后台配置cors,允许特定请求跨域 . 并不是所有的后台都懂cors,不能指望后台给单独处理.
    // 1.1  https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
    // 2. 开发阶段如何处理跨域. 通过webpack的devServer的proxy配置实现突破跨域
    // 3. 通过nginx配置转发,实现跨域.一般后台处理
    // create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // baseURL: settingFile.host, //后台帮我们做好跨域请求后可以使用该行代码,但往往后台不知道怎么做,所以我们需要在config.js进行跨域请求 // 会自动在pai前面追加 补充的url:  url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        var token = getToken();
        if (token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['bufan-token'] = token //请求头配置
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
        /**
         * If you want to get http information such as headers or status
         * Please return  response => response
         */

        /**
         * Determine the request status by custom code
         * Here is just an example
         * You can also judge the status by HTTP Status Code
         */
        response => {
            const res = response.data
            if (res.tokenCode == '5000' || res.tokenCode == '5001') {
                Message({
                        message: '发现未登录,请重新登录',
                        type: 'error',
                        duration: 3 * 1000
                    })
                    //  清除痕迹
                clearLogin()
                    //  强制跳转
                router.push('/login')
                return Promise.reject(new Error(res.message || 'Error'))
            }
            //剩余5分钟过期,自动续期
            if (res.tokenCode == '5002') {
                //   获取新的token直接存入ls即可,更新token,在下一次请求中会默认携带token
                setToken(res.refresh_token)
            }

            return res

        },
        error => {
            console.log('err' + error) // for debug
            Message({
                message: error.message,
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(error)
        }
    )
    /**
     * 重新包装service 保持get和post统一 减少api代买封装量
     *
     */
function http(config) {
    if (config.method.toLowerCase() === 'get') {
        if (config.kv) {
            config.params = config.kv
        }
    } else {
        // 如果是post 修改content-type
        config.headers = { 'content-type': 'application/x-www-form-urlencoded' };

        if (config.kv) {
            // 利用qs对数据进行序列化处理
            // user: {name: '张三',age: 30} => user[name]='张三' /  user.name='张三'
            config.data = qs.stringify(config.kv, { allowDots: true });
        }
    }
    return service(config)
}

export default http